<?php

namespace app\controller\car;

use app\BaseController;
use app\model\Supplier;
use think\facade\Cache;
use think\helper\Str;
use think\response\Json;

class Auth extends BaseController
{
    public function login(): Json
    {
        return $this->handle(function () {
            $param = $this->request->post();
            $account = $this->app->make(Supplier::class)->where("out_key", $param['username'])->where('state', 1)->find();
            if (empty($account)) throw new \Exception('账号不存在');
            if (!checkPassword($param['password'], $account['password'], $account['password_token'])) throw new \Exception('密码错误');
            $token = $this->setToken();
            $ttl = 3600 * 24 * 7;
            Cache::set("car_$token", ["id"=>$account['id'],"verify_time"=>strtotime("+7 day")], $ttl);
            return ['token' => $token,'id'=>$account['id']];
        });
    }

    public function check()
    {
        return $this->handle(function () {
            return $this->request->supplier ?? [];
         });
    }

    protected function setToken(): string
    {
        $code = Str::random(32, 9);
        if (Cache::has("car_$code")) {
            return $this->setToken();
        }
        return $code;
    }
}
